<template>
  <div class="details" v-if="skuData">
    <Heads types="details" :title="skuData.goods_info.title"></Heads>

    <!-- 滑动区域 -->
    <div class="content">
      <!-- 轮播 -->
      <div class="slide-container">
        <van-swipe :loop="false" @change="onChange">
          <van-swipe-item v-for="(item, i) in banner" :key="i">
            <van-image :src="item" width="100%" height="100%">
              <template v-slot:loading>
                <van-loading type="spinner" size="20" />
              </template>
            </van-image>
          </van-swipe-item>

          <div class="custom-indicator" slot="indicator">{{ current + 1 }}/{{banner.length}}</div>
        </van-swipe>
      </div>
      <!-- 名称 -->
      <div style="margin: 8px 0">
        <van-collapse v-model="activeNames">
          <van-collapse-item name="details">
            <div slot="title" :style="{tetxAlign: 'left'}">{{skuData.goods_info.title}}</div>
            <div slot="default" :style="{tetxAlign: 'left'}">暂无描述~~~</div>
          </van-collapse-item>
        </van-collapse>
      </div>
      <!-- 服务 -->
      <van-cell-group>
        <van-field label="13号仓库" readonly>
          <div slot="input">
            <van-icon name="clock-o" size="16px" style="vertical-align: middle;" />
            {{deliveryTime}}
          </div>
        </van-field>
        <van-field label="服务" value="全场满99包邮 | 支持7天无理由退货" readonly />
      </van-cell-group>
    </div>

    <!-- 店铺 -->
    <store-fronts></store-fronts>
    <!-- Html渲染区 -->
    <detail-html></detail-html>
    <!-- sku -->
    <div class="sku-container" :style="{'text-align':'left'}">
      <!-- v-model="showCustom" // 显示
        :sku="skuData.sku" // tree list(tree的组合) messages
        :goods="skuData.goods_info"
        :goods-id="skuData.goods_id"
        :hide-stock="skuData.sku.hide_stock" // 是否显示商品剩余库存
        :quota="skuData.quota" // 限购数，0 表示不限购
        :quota-used="skuData.quota_used" // 已经购买过的数量
        :start-sale-num="skuData.start_sale_num" // 起售
        :properties="skuData.properties" // 附加属性
        reset-stepper-on-hide // 隐藏时重置选择的商品数量
        safe-area-inset-bottom // 底部安全区适配
        :initial-sku="skuData.initialSku" //初始选中
        :message-config="messageConfig" // 信息
        :custom-sku-validator="customSkuValidator" // 提示
      ref="getSku"-->
      <van-sku
        v-model="showCustom"
        :sku="skuData.sku"
        :goods="skuData.goods_info"
        :goods-id="skuData.goods_id"
        :hide-stock="skuData.sku.hide_stock"
        :quota="skuData.quota"
        :quota-used="skuData.quota_used"
        :start-sale-num="skuData.start_sale_num"
        :properties="skuData.properties"
        reset-stepper-on-hide
        safe-area-inset-bottom
        :initial-sku="skuData.initialSku"
        :message-config="messageConfig"
        :custom-sku-validator="customSkuValidator"
        @buy-clicked="onDefineClicked"
        :show-add-cart-btn="false"
        buy-text="确定"
        ref="getSku"
      >
        <template #sku-header-price="{ price }">
          <div class="van-sku__goods-price">
            <span class="van-sku__price-symbol">￥</span>
            <span class="van-sku__price-num">{{ price }}</span>
          </div>
        </template>
        <!-- <template #sku-actions="{ skuEventBus }"> 自定义按钮不支持提醒没选 -->
      </van-sku>
    </div>
    <!-- .sku-end. -->

    <!-- 底部动作 -->
    <div v-if="skuData" class="action-container">
      <van-goods-action safe-area-inset-bottom>
        <van-goods-action-icon icon="cart-o" :info="cartNum" text="购物车" :to="{name: 'Shopcart'}" />
        <van-goods-action-icon
          class="collect-icon"
          ref="collectIcon"
          :icon="collectFlag ? 'star' : 'star-o'"
          :text="collectFlag ? '已收藏' : '收藏'"
          color="#ff5000"
          @click="onCollectClicked"
        />
        <van-goods-action-icon icon text color="#07c160" />
        <van-goods-action-button type="warning" text="加入购物车" @click="onShowCustom('add-cart')" />
        <van-goods-action-button type="danger" text="立即购买" @click="onShowCustom('buy')" />
      </van-goods-action>
    </div>
  </div>
</template>

<script>
import { get, post } from "@/utils/axios";
import DetailHtml from '@/components/detail/DetailHtml.vue'
import StoreFronts from '@/components/detail/StoreFronts.vue'

import { mapGetters, mapMutations, mapState, mapActions } from "vuex";
// import { skuData } from './data.js'
// import { LIMIT_TYPE } from './constants' // 用于限购
import Vue from "vue";
import {
  Field,
  Sku,
  Toast,
  GoodsAction,
  GoodsActionButton,
  GoodsActionIcon,
  Collapse,
  CollapseItem,
  Cell,
  CellGroup
} from "vant";
Vue.use(Sku)
  .use(Field)
  .use(Toast)
  .use(GoodsAction)
  .use(GoodsActionButton)
  .use(GoodsActionIcon)
  .use(Collapse)
  .use(CollapseItem)
  .use(Cell)
  .use(CellGroup);

export default {
  data() {
    return {
      activeNames: [""],
      // isCollect: false,
      banner: [
        "https://img.alicdn.com/imgextra/i1/88/O1CN012FcSWb1CWLRGHhwjk_!!88-0-luban.jpg_q100.jpg",
        "https://img.alicdn.com/simba/img/TB1o6YOsqL7gK0jSZFBSutZZpXa.jpg",
        "https://img.alicdn.com/tps/i4/TB1lUY_v.T1gK0jSZFrSuwNCXXa.jpg",
        "https://img.alicdn.com/simba/img/TB1457mo7Y2gK0jSZFgSuw5OFXa.jpg",
        "https://img.alicdn.com/imgextra/i2/112/O1CN01z5O8Zo1ChKwfTT4Zs_!!112-0-luban.jpg_q100.jpg"
      ], // 轮播
      current: 0, // 轮播index
      skuData: null,
      showCustom: false, // 是否显示sku
      showStepper: false,
      showSoldout: false,
      closeOnClickOverlay: true,
      customSkuValidator: () => "请选择商品属性~",
      /**  customStepperConfig: {
      //   quotaText: '单次限购100件',
      //   stockFormatter: stock => `剩余${stock}件`,
      //   handleOverLimit: data => {
      //     const { action, limitType, quota, startSaleNum = 1 } = data
      //     if (action === 'minus') {
      //       Toast(
      //         startSaleNum > 1 ? `${startSaleNum}件起售` : '至少选择一件商品'
      //       )
      //     } else if (action === 'plus') {
      //       if (limitType === LIMIT_TYPE.QUOTA_LIMIT) {
      //         Toast(`限购${quota}件`)
      //       } else {
      //         Toast('库存不够了')
      //       }
      //     }
      //   }
      // },
      */
      messageConfig: {
        uploadImg: (file, img) =>
          new Promise(resolve => {
            setTimeout(() => resolve(img), 1000);
          }),
        uploadMaxSize: 3
      }
    };
  },
  components: {
    DetailHtml,
    StoreFronts
  },
  computed: {
    ...mapGetters("cartModule", ["cartNum"]),
    ...mapState("userModule", ["token", "userinfo"]),
    deliveryTime() {
      const dates = new Date();
      return `预计${dates.getFullYear()}/${dates.getMonth() +
        1}/${dates.getDate() + 3}后发货`;
    },
    collectFlag() {
      return (Array.isArray(this.userinfo.collections) && this.userinfo.collections.includes(this.$route.params.tradeItemId))
    }
  },
  methods: {
    ...mapMutations("footerModule", ["FOOTERSHOW"]),
    ...mapMutations("payModule", ["SETTYPES", "SETOBJ"]),
    ...mapActions("userModule", ["ADDUSERHISTORY", "SETUSERCOLLECT"]),
    ...mapActions('cartModule', ['getCartListAction']),
    onChange(index) {
      // 轮播显示页码
      this.current = index;
    },
    onShowCustom(type) {
      // goods-action底部的加购和购买
      this.showCustom = true;
      this.skuType = type;
    },
    onCollectClicked() {
      // goods-action的收藏
      if (!this.token) return
      this.SETUSERCOLLECT({
        goods_id: this.$route.params.tradeItemId,
        isCollect: this.collectFlag
      })
    },
    searchTree(sType, sVal) {
      const arrKS = this.skuData.sku.tree.filter(treeKS => {
        return treeKS.k_s === sType;
      });
      const arrV = arrKS[0].v.filter(treeV => {
        return treeV.id === sVal;
      });
      return arrV[0].name;
    },
    onDefineClicked() {
      // Toast('buy:' + JSON.stringify(data))
      // 点击确定按钮
      if (!this.$refs.getSku.getSkuData().selectedSkuComb) {
        Toast({
          message: "请选择商品属性~",
          closeOnClick: true
        });
      } else {
        if (this.skuType === "buy") {
          if (this.token) {
            let obj = this.$refs.getSku.getSkuData();
            obj = {
              ...obj,
              // user: token,
              s1: this.searchTree("s1", obj.selectedSkuComb.s1),
              s2: this.searchTree("s2", obj.selectedSkuComb.s2),
              goods_info: this.skuData.goods_info
            };

            this.SETTYPES("obj");
            this.SETOBJ(obj);
            this.$router.push({ name: "Paymentpage" });
          } else {
            Toast({
              message: "未登录状态,无法操作",
              closeOnClick: true
            });
          }
        } else {
          // console.log('加购')
          // 先数据库,再默认头像
          // console.log(this.$refs.getSku.getSkuData())
          if (this.token) {
            post({
              url: "/hybrid/uni/addcart",
              data: {
                // token,
                info: this.$refs.getSku.getSkuData()
              }
            }).then(res => {
              Toast({
                message: res.msg,
                closeOnClick: true
              });
              post({
                url: "/hybrid/uni/cart",
                // data: { user: token }
              }).then(res => {
                this.getCartListAction()
              });
            });
          } else {
            Toast({
              message: "未登录状态,无法操作",
              closeOnClick: true
            });
          }
        }
      }
    }
  },
  mounted() {
    const detailsId = this.$route.params.tradeItemId;
    this.FOOTERSHOW(false);
    get({
      url: "/hybrid/uni/details",
      data: {
        tradeItemId: detailsId
      }
    }).then(res => {
      if (res.code === 200) {
        this.skuData = res.result;
        this.banner = [res.result.goods_info.picture, ...this.banner];
      } else {
        this.skuData = null;
      }
    });
    // 增加浏览历史记录
    if (this.token) {
      this.ADDUSERHISTORY(detailsId);
    }
  },
  destroyed() {
    this.FOOTERSHOW(true);
  }
};
</script>

<style lang="scss" scoped>
.details {
  .content {
    // height: 11.5rem;
    overflow-y: auto;
    .slide-container {
      width: 100vw;
      // height: 5.5rem;
      height: 200px;
      position: relative;
      .van-swipe {
        height: 100%;
        .van-swipe__track {
          .van-swipe-item {
            width: 100%;
            height: 100%;
          }
        }
        .custom-indicator {
          position: absolute;
          right: 4px;
          bottom: 4px;
          width: 26px;
          height: 14px;
          font-size: 14px;
          line-height: 16px;
          text-align: center;
          border-radius: 6px;
          color: aliceblue;
          background: rgba(0, 0, 0, 0.3);
        }
      }
    }
  }
}
</style>
